package com.buss.customer.dao.impl;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.buss.core.dic.RecordStatus;
import com.buss.core.persistence.BaseDao;
import com.buss.core.persistence.OrderBy;
import com.buss.core.persistence.Paginalbe;
import com.buss.core.persistence.ResultList;
import com.buss.core.utils.StringUtil;
import com.buss.customer.dao.CustomerDao;
import com.buss.customer.model.Customer;

@Repository
public class CustomerDaoImpl implements CustomerDao {

	@Autowired
	private BaseDao<Customer> baseDao;
	
	@Override
	public Customer saveCustomer(Customer customer) {
		return baseDao.saveOrEdit(customer);
	}

	@Override
	public void editCustomer(Customer customer) {
		baseDao.edit(customer);
	}

	@Override
	public void removeCustomer(Long[] ids) {
		String sql = "delete from Customer customer where customer.id in (:ids)";
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("ids", ids);
		baseDao.excuteHsql(sql, params);
	}

	@Override
	public Customer loadCustomer(Long id) {		
		return baseDao.get(id, Customer.class);
	}

	@Override
	public ResultList<Customer> queryCustomer(String companyId, Long[] classIds,
			String name, String mnemonic, Long salesId, Boolean isCustomer,
			Boolean isSupplier, RecordStatus status,Paginalbe page,OrderBy orderBy) {
		String sql = "select customer from Customer customer left join customer.saleses saleses where customer.companyId = :companyId ";
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("companyId", companyId);
		if(classIds != null && classIds.length > 0){
			sql += " and customer.customerClass.id in (:classIds) ";
			params.put("classIds", classIds);
		}
		if(StringUtil.isNotEmpty(name)){
			sql += " and customer.name like :name ";
			params.put("name", "%" + name + "%");
		}
		if(StringUtil.isNotEmpty(mnemonic)){
			sql += " and customer.mnemonic like :mnemonic ";
			params.put("mnemonic", "%" + mnemonic + "%");
		}
		if(salesId != null){
			sql += " and saleses.id = :salesId or customer.isOpenToSales = :isOpenToSales ";
			params.put("salesId", salesId);
			params.put("isOpenToSales", true);
		}else{
			sql += " and customer.isOpenToSales = :isOpenToSales ";			
			params.put("isOpenToSales", true);
		}
		if(isCustomer != null){
			sql += " and customer.isCustomer = :isCustomer ";
			params.put("isCustomer", isCustomer);
		}
		if(isSupplier != null){
			sql += " and customer.isSupplier = :isSupplier ";
			params.put("isSupplier", isSupplier);
		}
		if(orderBy != null){
			sql += orderBy.aggOrder("customer");
		}
		
		return baseDao.queryHsql(sql, params, page);
	}

}
